import json
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import tkinter as tk
from tkinter import ttk, scrolledtext
from threading import Thread
import time

class PDDIndexCrawlerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("拼多多首页元素提取工具")
        self.root.geometry("900x700")
        self.root.configure(bg="#f5f5f5")
        
        # 设置Chrome选项
        self.chrome_options = Options()
        self.chrome_options.add_argument("--disable-gpu")
        self.chrome_options.add_argument("--no-sandbox")
        self.chrome_options.add_argument("--disable-dev-shm-usage")
        self.chrome_options.add_argument("--disable-software-rasterizer")
        self.chrome_options.add_argument("--disable-webgl")
        self.chrome_options.add_argument("--disable-features=VizDisplayCompositor")
       
        self.driver = None
        self.cookie_file = r"G:\py\美团\pdd_cookies.json"
        self.url = "https://mobile.pinduoduo.com/search_result.html?search_key=%E6%84%9F%E5%86%92%E7%81%B5&search_met_track=history&search_type=goods&source=index&options=3&refer_search_met_pos=0&refer_page_el_sn=99887&refer_page_name=login&refer_page_id=10169_1757122553288_h7sdfs7qdz&refer_page_sn=10169"
        self.setup_ui()
        
    def setup_ui(self):
        # 标题
        title_label = tk.Label(self.root, text="拼多多首页元素提取工具", font=("Arial", 18, "bold"), 
                              fg="#ff453a", bg="#f5f5f5")
        title_label.pack(pady=20)
        
        # 说明
        desc_label = tk.Label(self.root, text="此工具读取Cookies并提取首页class='J9WPy2Wu'的元素文本", 
                             font=("Arial", 12), bg="#f5f5f5", fg="#666")
        desc_label.pack(pady=5)
        
        # URL显示（只读）
        url_frame = tk.Frame(self.root, bg="#f5f5f5")
        url_frame.pack(pady=10, padx=20, fill="x")
        
        tk.Label(url_frame, text="拼多多首页URL:", font=("Arial", 10), bg="#f5f5f5").pack(anchor="w")
        
        self.url_var = tk.StringVar(value=self.url)
        url_entry = tk.Entry(url_frame, textvariable=self.url_var, font=("Arial", 10), width=70, state="readonly")
        url_entry.pack(pady=5, fill="x")
        
        # Cookies文件路径显示（只读）
        cookie_frame = tk.Frame(self.root, bg="#f5f5f5")
        cookie_frame.pack(pady=10, padx=20, fill="x")
        
        tk.Label(cookie_frame, text="Cookies文件路径:", font=("Arial", 10), bg="#f5f5f5").pack(anchor="w")
        
        self.cookie_var = tk.StringVar(value=self.cookie_file)
        cookie_entry = tk.Entry(cookie_frame, textvariable=self.cookie_var, font=("Arial", 10), width=70, state="readonly")
        cookie_entry.pack(pady=5, fill="x")
        
        # 按钮框架
        btn_frame = tk.Frame(self.root, bg="#f5f5f5")
        btn_frame.pack(pady=15)
        
        self.start_btn = tk.Button(btn_frame, text="开始提取", command=self.start_crawling, 
                                  bg="#ff453a", fg="white", font=("Arial", 12), width=15)
        self.start_btn.pack(side="left", padx=10)
        
        self.clear_btn = tk.Button(btn_frame, text="清除结果", command=self.clear_results, 
                                  bg="#666", fg="white", font=("Arial", 12), width=15)
        self.clear_btn.pack(side="left", padx=10)
        
        # 进度条
        self.progress = ttk.Progressbar(self.root, mode="indeterminate")
        self.progress.pack(pady=10, padx=20, fill="x")
        
        # 结果展示区域
        result_frame = tk.Frame(self.root, bg="#f5f5f5")
        result_frame.pack(pady=10, padx=20, fill="both", expand=True)
        
        tk.Label(result_frame, text="提取结果:", font=("Arial", 12, "bold"), bg="#f5f5f5").pack(anchor="w")
        
        self.result_text = scrolledtext.ScrolledText(result_frame, height=20, width=100, font=("Arial", 10))
        self.result_text.pack(pady=10, fill="both", expand=True)
        
        # 状态栏
        self.status_var = tk.StringVar(value="就绪")
        status_bar = tk.Label(self.root, textvariable=self.status_var, relief="sunken", anchor="w", 
                             font=("Arial", 10), bg="white", fg="#333")
        status_bar.pack(side="bottom", fill="x")
    
    def load_cookies(self):
        """从文件加载Cookies"""
        try:
            if os.path.exists(self.cookie_file):
                with open(self.cookie_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            raise FileNotFoundError(f"Cookies文件 {self.cookie_file} 不存在")
        except Exception as e:
            self.root.after(0, self.show_error, f"加载Cookies失败: {str(e)}")
            return None
    
    def start_crawling(self):
        # 禁用开始按钮，防止重复点击
        self.start_btn.config(state="disabled")
        self.progress.start(10)
        self.status_var.set("正在初始化浏览器...")
        
        # 在新线程中运行提取
        thread = Thread(target=self.crawl_data)
        thread.daemon = True
        thread.start()
    
    def crawl_data(self):
        try:
            # 初始化浏览器
            self.driver = webdriver.Chrome(options=self.chrome_options)
            
            # 加载Cookies
            self.status_var.set("正在加载Cookies...")
            cookies = self.load_cookies()
            if not cookies:
                raise Exception("无法加载Cookies")
            
            # 访问域名以设置Cookies
            self.driver.get("https://mobile.pinduoduo.com")
            for cookie in cookies:
                try:
                    self.driver.add_cookie(cookie)
                except Exception as e:
                    self.root.after(0, self.show_error, f"设置Cookie失败: {str(e)}")
                    return
            
            # 访问目标URL
            self.status_var.set("正在加载首页...")
            self.driver.get(self.url)
            
            # 等待页面加载
            WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CLASS_NAME, "J9WPy2Wu"))
            )
            
            # 滚动页面以加载所有内容
            self.status_var.set("正在滚动页面...")
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(2)  # 等待动态内容加载
            
            # 查找所有class="J9WPy2Wu"的元素
            self.status_var.set("正在提取元素文本...")
            elements = self.driver.find_elements(By.CLASS_NAME, "J9WPy2Wu")
            
            # 提取文本
            results = []
            if not elements:
                results.append("未找到class='J9WPy2Wu'的元素\n")
            else:
                for i, element in enumerate(elements):
                    text = element.text.strip() or "文本不可用"
                    results.append(f"元素 {i+1}:\n{text}\n{'-'*50}\n")
            
            # 在UI线程中更新结果
            self.root.after(0, self.update_results, results)
            
        except Exception as e:
            error_msg = f"提取过程中出错: {str(e)}"
            self.root.after(0, self.show_error, error_msg)
        
        finally:
            if self.driver:
                self.driver.quit()
            
            self.root.after(0, self.crawling_finished)
    
    def update_results(self, results):
        self.result_text.delete(1.0, tk.END)
        for result in results:
            self.result_text.insert(tk.END, result)
        
        self.status_var.set(f"提取完成，共找到 {len(results)} 个元素")
    
    def show_error(self, error_msg):
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, error_msg)
        self.status_var.set("提取失败")
    
    def crawling_finished(self):
        self.progress.stop()
        self.start_btn.config(state="normal")
    
    def clear_results(self):
        self.result_text.delete(1.0, tk.END)
        self.status_var.set("已清除结果")
    
    def __del__(self):
        if self.driver:
            self.driver.quit()

if __name__ == "__main__":
    root = tk.Tk()
    app = PDDIndexCrawlerApp(root)
    root.mainloop()